package com.wangshuqi.jdbc.dao;

import com.wangshuqi.jdbc.util.JDBCUtil;
import jdk.nashorn.internal.scripts.JD;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseDAO<T> {

    private Class<T> clazz;

    // 获取T的Class对象，获取泛型的类型，泛型是在被子类继承时才确定
    public BaseDAO() {
        // getGenericSuperclass()用来获取当前类的父类的类型
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        ParameterizedType paramType = (ParameterizedType) genericSuperclass;// ParameterizedType表示的是带泛型的类型
        // 获取具体的泛型类型 getActualTypeArguments获取具体的泛型的类型
        Type[] actualTypes = paramType.getActualTypeArguments();
        clazz = (Class<T>) actualTypes[0];
    }

    /**
     * 增删改操作
     *
     * @param connection
     * @param sql
     * @param args
     * @return int
     * @author codewsq
     * @date 2021/8/27 0027 10:15
     */
    public int saveOrUpdateOrDelete(Connection connection, String sql, Object... args) {
        PreparedStatement ps = null;
        int updateCount = 0;
        try {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            updateCount = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(null, ps);
        }

        return updateCount;
    }

    /**
     * @param connection
     * @param sql
     * @param args
     * @return T
     * @author codewsq
     * @date 2021/8/27 0027 10:29
     */
    public T selectBean(Connection connection, String sql, Object... args) {
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            if (resultSet.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, resultSet.getObject(i + 1));
                }
                return t;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(null, ps, resultSet);
        }
        return null;
    }

    /**
     * @param connection
     * @param sql
     * @param args
     * @return List<T>
     * @author codewsq
     * @date 2021/8/27 0027 10:29
     */
    public List<T> selectBeanList(Connection connection, String sql, Object... args) {
        List<T> resultList = new ArrayList<>();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (resultSet.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, resultSet.getObject(i + 1));
                }
                resultList.add(t);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(null, ps, resultSet);
        }
        return resultList;
    }

    /**
     * 查询特殊类型 - 比如 多少条记录，或者某个字段值
     *
     * @param connection
     * @param sql
     * @param args
     * @return List<T>
     * @author codewsq
     * @date 2021/8/27 0027 10:29
     */
    public <E> E selectValue(Connection connection, String sql, Object... args) {
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            resultSet = ps.executeQuery();
            if (resultSet.next()) {
                return (E) resultSet.getObject(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(null, ps, resultSet);
        }
        return null;
    }

}
